<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form
          @submit.native.prevent
          label-width="80px"
          label-position="left"
        >
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-select
                v-model="listQuery.fsiteNo"
                disabled
                clearable
                filterable
                class="filter-item"
                placeholder="请选择场地名称"
              >
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目名称">
              <el-select
                v-model="listQuery.fairitemw"
                clearable
                filterable
                class="filter-item"
                placeholder="请选择项目名称"
              >
                <el-option
                  v-for="item in sTsAiritemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleFilter">查找</el-button>
              <el-button type="success" @click="handleCreate">添加</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <!-- 查询结果 -->
        <JNPF-table v-loading="listLoading" :data="list">
          <el-table-column
            align="center"
            :width="buttonColor.operationTwo"
            label="操作"
            class-name="small-padding"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="handleUpdate(scope.row)"
                >编辑</el-button
              >
              <el-button type="text" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            :width="buttonColor.line"
            :index="indexMethod"
            align="center"
            label="序"
            type="index"
          />
          <el-table-column
            :formatter="formatSite"
            align="left"
            label="客户名称"
            prop="fsiteNo"
            :width="buttonColor.name"
          />
          <el-table-column
            :formatter="formatSTsAiritem"
            align="left"
            label="项目名称"
            prop="fairitem"
            width="120px"
          />
          <el-table-column
            align="center"
            label="起始值"
            :width="buttonColor.num"
            prop="fbegnum"
          />
          <el-table-column
            align="center"
            label="结束值"
            :width="buttonColor.num"
            prop="fendnum"
          />
          <el-table-column
            align="left"
            label="报警说明"
            width="550px"
            prop="fdescribe"
          />
          <el-table-column align="left" label="设定状态" prop="fstate">
            <template slot-scope="scope">
              <span
                :style="{ color: buttonColor.statedisable }"
                v-if="scope.row.fstate === 0"
                >{{ scope.row.fstate | statusFilter }}</span
              >
              <span :style="{ color: buttonColor.statestart }" v-else>{{
                scope.row.fstate | statusFilter
              }}</span>
            </template>
          </el-table-column>
        </JNPF-table>
        <paginations
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
        />
      </div>
    </div>
    <el-dialog
      :fullscreen="true"
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-tabs type="border-card">
        <el-tab-pane
          label="头表"
          :style="{ height: screenHeight - 230 + 'px' }"
        >
          <el-row class="JNPF-common-search-box" :gutter="16">
            <el-form
              @submit.native.prevent
              label-width="80px"
              label-position="left"
              ref="dataForm"
              :rules="rules"
              :model="dataForm"
            >
              <el-col :span="6">
                <el-form-item label="客户名称" prop="fsiteNo">
                  <el-select
                    v-model="dataForm.fsiteNo"
                    disabled
                    clearable
                    filterable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in fsiteNoBelongOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="风险等级" prop="flevelno">
                  <el-select
                    clearable
                    filterable
                    v-model="dataForm.flevelno"
                    class="filter-item"
                    placeholder="请选择状态"
                  >
                    <el-option
                      v-for="item in getListAreas"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="设定状态" prop="fstate">
                  <el-select
                    v-model="dataForm.fstate"
                    class="filter-item"
                    placeholder="请选择状态"
                  >
                    <el-option
                      v-for="(key, value) in statusMap"
                      :key="key"
                      :label="key"
                      :value="value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发送邮件" prop="fsendemail">
                  <el-select
                    v-model="dataForm.fsendemail"
                    class="filter-item"
                    placeholder="请选择状态"
                  >
                    <el-option
                      v-for="(key, value) in sendStatusMap2"
                      :key="key"
                      :label="key"
                      :value="value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="空气项目" prop="fairitem">
                  <el-select
                    v-model="dataForm.fairitem"
                    clearable
                    filterable
                    placeholder="请选择"
                    @change="changeFscoreFlag(dataForm.fairitem)"
                  >
                    <el-option
                      v-for="item in sTsAiritemOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="起始值" prop="fbegnum">
                  <el-input v-model="dataForm.fbegnum" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="结束值" prop="fendnum">
                  <el-input v-model="dataForm.fendnum" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发送短信" prop="fsendmsg">
                  <el-select
                    v-model="dataForm.fsendmsg"
                    class="filter-item"
                    placeholder="请选择状态"
                  >
                    <el-option
                      v-for="(key, value) in sendStatusMap2"
                      :key="key"
                      :label="key"
                      :value="value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="报警说明" prop="fdescribe">
                  <el-input v-model="dataForm.fdescribe" />
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="明细表"  :style="{ height: screenHeight - 230 + 'px' }">
          <div class="transferbox">
            <el-transfer :titles="['未选', '已选']" v-model="chenglist" :data="transferlist"></el-transfer>
          </div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()" type="info">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="createData"
          >确定</el-button
        >
        <el-button v-else @click="updateData" type="primary">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style scoped>
 .transferbox{
    display: flex;
    justify-content: center;
    align-content: center;
    height: 100%;
 }
 .el-transfer{
    display: flex !important;
    align-items: center !important;
    width: 660px;
 }
</style>
<script>
import {
  listPointByFsiteNo,
  listUserByFsiteNo,
  sTsAiritemOptions,
} from "@/api/airAlarm";
import {
  listtsAirwarring,
  createtsAirwarring,
  updatetsAirwarring,
  deletetsAirwarring,
} from "@/api/tsAirwarring";
import { fsiteOptionsByLevel, getListArea } from "@/api/area"; // fsiteNoBelongOptions
import Pagination from "@/components/Pagination";
import moment from "moment/moment";
import { tableColor, titleColor, buttonColor } from "@/filters/index";

const statusMap = {
  0: "停止",
  1: "启用",
};

const flagMap = {
  1: "学校",
  2: "教室",
};

// const sendStatusMap = {
//   0: '未发送',
//   1: '已发送'
// }

const sendStatusMap2 = {
  0: "否",
  1: "是",
};


export default {
  name: "CabAlarmSet",
  components: { Pagination },
  filters: {
    statusFilter(type) {
      return statusMap[type];
    },
    flagFilter(type) {
      return flagMap[type];
    },
    sendStatusFilter(type) {
      return sendStatusMap2[type];
    } /*,
    fstorageflagFilter(type) {
      debugger
      return atsPointsMap[type]
    }*/,
  },
  data() {
    return {
      panelHeightUser: 0,
      screenHeight: document.body.clientHeight,
      panelHeight: 0,
      buttonColor,
      chenglist:[],
      transferlist:[],
      getListAreas: null,
      multipleSelection: [],
      multipleSelection2: [],
      multiple: [],
      multiple2: [],
      atsUsersTmp: [],
      atsPointsTmp: [],
      list: null,
      total: 0,
      fsiteNoBelongOptions: null,
      sTsAiritemOptions: null,
      fscoreFlagStatus: false,
      // fscoreFlagStatus2: false,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fairitemw:undefined,
        fsiteNo: this.$store.state.user.fsiteNo,
        fairitem: undefined,
        sort: "create_time",
        order: "desc",
      },
      statusMap,
      flagMap,
      // sendStatusMap,
      sendStatusMap2,
      dataForm: {
        id: undefined,
        fwarringno: undefined,
        fsiteNo: undefined,
        fscoreFlag: undefined,
        fairitem: undefined,
        fbegnum: undefined,
        fendnum: undefined,
        fdescribe: undefined,
        fsendmsg: undefined,
        flevelno: undefined,
        fsendemail: undefined,
        fstate: undefined,
        atsUsers: [],
        atsPoints: [],
      },
      dataForm2: {
        fuserno: undefined,
        username: undefined,
      },
      atsUsers: null,
      atsPoints: null,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogStatus: "",
      dialogStatus1: "",
      dialogStatus2: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      tableColor: tableColor,
      titleColor: titleColor,
      rules: {
        fsiteNo: [
          { required: true, message: "学校名称不能为空", trigger: "blur" },
        ],
        /*fscoreFlag: [
          { required: true, message: '统计范围不能为空', trigger: 'blur' }
        ],*/
        fairitem: [
          { required: true, message: "空气项目名称不能为空", trigger: "blur" },
        ],
        fbegnum: [
          { required: true, message: "起始值不能为空", trigger: "blur" },
        ],
        fendnum: [
          { required: true, message: "结束值不能为空", trigger: "blur" },
        ],
        fdescribe: [
          { required: true, message: "报警说明不能为空", trigger: "blur" },
        ],
        fsendmsg: [
          { required: true, message: "是否发送短信不能为空", trigger: "blur" },
        ],
        flevelno: [
          { required: true, message: "风险等级不能为空", trigger: "blur" },
        ],
        fsendemail: [
          { required: true, message: "是否发送邮件不能为空", trigger: "blur" },
        ],
        fstate: [
          { required: true, message: "设定状态不能为空", trigger: "blur" },
        ],
      },
      permissionDialogFormVisible: false,
      systemPermissions: null,
      assignedPermissions: null,
      permissionForm: {
        roleId: undefined,
        permIds: [],
      },
    };
  },
  created() {
    this.panelHeight = document.documentElement.clientHeight - 335;
    this.panelHeightUser = document.documentElement.clientHeight - 380;
    this.getList();
    fsiteOptionsByLevel(3) // fsiteNoBelongOptions(2)
      .then((response) => {
        this.fsiteNoBelongOptions = response.data.data.list;
      })
      .catch(() => {
        this.fsiteNoBelongOptions = [];
      });
    sTsAiritemOptions()
      .then((response) => {
        this.sTsAiritemOptions = response.data.data.list;
      })
      .catch(() => {
        this.sTsAiritemOptions = [];
      });
    getListArea({ flag: 7 })
      .then((response) => {
        this.getListAreas = response.data.data.list;
      })
      .catch(() => {
        this.getListAreas = [];
      });
    getListArea({ flag: 28 })
      .then((response) => {
        this.atsPoints = response.data.data.list;
        response.data.data.list.forEach(res=>{
          this.transferlist.push({
            key: res.value,
            label:res.label
          })
        })
      })
      .catch(() => {
        this.atsPoints = [];
      });
  },
  methods: {
    formatflevelno: function (row, column) {
      if (this.getListAreas) {
        for (let i = 0; i < this.getListAreas.length; i++) {
          if (row.flevelno === this.getListAreas[i].value) {
            return this.getListAreas[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelectionChange2(val) {
      this.multipleSelection2 = val;
    },
    formatStatus: function (row, column) {
      return row.fsiteState === 1 ? "启用" : "禁用";
    },
    dateFormat(row, column) {
      const date = row[column.property];
      if (date === undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    formatSite: function (row, column) {
      if (this.fsiteNoBelongOptions) {
        for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
          if (row.fsiteNo === this.fsiteNoBelongOptions[i].value) {
            return this.fsiteNoBelongOptions[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    formatSTsAiritem: function (row, column) {
      if (this.sTsAiritemOptions) {
        for (let i = 0; i < this.sTsAiritemOptions.length; i++) {
          if (row.fairitem === this.sTsAiritemOptions[i].value) {
            return this.sTsAiritemOptions[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    formatFstorageflag: function (row, column) {
      if (this.atsPoints) {
        for (let i = 0; i < this.atsPoints.length; i++) {
          if (row.fstorageflag === this.atsPoints[i].value) {
            return this.atsPoints[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    getList() {
      this.listLoading = true;
      listtsAirwarring(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        fwarringno: undefined,
        fsiteNo: undefined,
        fscoreFlag: undefined,
        fairitem: undefined,
        fbegnum: undefined,
        fendnum: undefined,
        fdescribe: undefined,
        fsendmsg: undefined,
        flevelno: undefined,
        fsendemail: undefined,
        fstate: undefined,
        atsUsers: [],
        atsPoints: [],
      };
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });

      this.resetForm2();
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm2"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.addData2();
          this.dataForm.fscoreFlag = "1"; // 默认学校
          createtsAirwarring(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data);
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "添加空气报警设定成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.msg,
              });
            });
        }
      });
    },
    cancel() {
      this.dialogFormVisible = false;
      // for (var i in this.multiple) {
      //   var atsUser = this.multiple[i]
      //   for (var j in this.dataForm.atsUsers) {
      //     if (atsUser.fuserno === this.dataForm.atsUsers[j].fuserno) {
      //       this.dataForm.atsUsers.splice(j)
      //       break
      //     }
      //   }
      // }
      this.multiple = [];
      // for (var m in this.multiple2) {
      //   var atsPoint = this.multiple2[m]
      //   for (var n in this.dataForm.atsPoints) {
      //     if (atsPoint.fpointNo === this.dataForm.atsPoints[n].fpointNo) {
      //       this.dataForm.atsPoints.splice(n)
      //       break
      //     }
      //   }
      // }
      this.multiple2 = [];
      this.list.forEach((v) => {
        if (v.fwarringno === this.dataForm.fwarringno) {
          this.dataForm.atsUsers = this.atsUsersTmp;
          this.dataForm.atsPoints = this.atsPointsTmp;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
      this.$refs.multipleTable.clearSelection();
      this.resetForm2();
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm2"].clearValidate();
      });
    },
    addData() {
      this.dialogFormVisible1 = false;
      for (var i in this.multipleSelection) {
        var atsUser = this.multipleSelection[i];
        var canAdd = true;
        for (var j in this.dataForm.atsUsers) {
          if (atsUser.fuserno + "" === this.dataForm.atsUsers[j].fuserno) {
            canAdd = false;
            break;
          }
        }
        if (canAdd) {
          atsUser.fwarringno = this.dataForm.fwarringno;
          this.dataForm.atsUsers.push(atsUser);
          this.multiple.push(atsUser);
        }
      }
    },
    resetForm2() {
      this.dataForm2 = {
        fuserno: undefined,
        username: undefined,
      };
    },
    addData2() {
      var atsPoint=[];
      this.chenglist.forEach(item=>{
        atsPoint.push({
          fwarringno:this.dataForm.fwarringno,
          fstorageflag:item
        })
      })
      this.dataForm.atsPoints=atsPoint;
      this.multiple2=atsPoint;
      this.resetForm2();
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm2"].clearValidate();
      });
    },
    cancle1() {
      this.resetForm2();
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm2"].clearValidate();
      });
      this.$refs.multipleTable.clearSelection();
    },
    handleUpdate(row) {
      this.resetForm2();
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm2"].clearValidate();
      });
      this.chenglist=[];
      this.dataForm = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.dataForm.fscoreFlag = row.fscoreFlag.toString();
      this.dataForm.fstate = row.fstate.toString();
      this.dataForm.fsendmsg = row.fsendmsg.toString();
      this.dataForm.fsendemail = row.fsendemail.toString();
      this.atsUsersTmp = [];
      this.atsPointsTmp = [];
      row.atsPoints.forEach((v) => {
        this.atsUsersTmp.push(v);
        this.chenglist.push(v.fstorageflag)
      });
      row.atsPoints.forEach((v) => {
        this.atsPointsTmp.push(v);
      });
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate1(fsiteNo) {
      if (fsiteNo == null) {
        this.$notify.info({
          title: "",
          message: "请先选择学校",
        });
        return;
      }
      listUserByFsiteNo(fsiteNo)
        .then((response) => {
          this.atsUsers = response.data.data.list;
        })
        .catch(() => {
          this.atsUsers = [];
        });
      this.dialogStatus1 = "update";
      this.dialogFormVisible1 = true;
      this.multipleSelection = [];
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },
    handleUpdate2() {
      /*listPointByFsiteNo(fsiteNo)
        .then(response => {
          this.atsPoints = response.data.data.list
        })*/
      this.dialogStatus2 = "update";
      this.dialogFormVisible2 = true;
      this.multipleSelection2 = [];
      this.$nextTick(() => {
        this.$refs["dataForm2"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.addData2();
          this.dataForm.fscoreFlag = "1"; // 默认学校
          updatetsAirwarring(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.fwarringno === this.dataForm.fwarringno) {
                  const index = this.list.indexOf(v);
                  this.dataForm.fstate = parseInt(this.dataForm.fstate);
                  this.dataForm.fsendmsg = parseInt(this.dataForm.fsendmsg);
                  this.dataForm.fsendemail = parseInt(this.dataForm.fsendemail);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "更新管理员成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.msg,
              });
            });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("是否要删除该空气报警设定", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deletetsAirwarring(row)
          .then((response) => {
            this.$notify.success({
              title: "成功",
              message: "删除空气报警设定成功",
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.msg,
            });
          });
      });
    },
    handleDelete1(row) {
      this.dataForm.atsUsers.pop(row);
    },
    handleDelete2(row) {
      const index = this.dataForm.atsPoints.indexOf(row);
      this.dataForm.atsPoints.splice(index, 1);
    },
    indexMethod(index) {
      index = index + 1;
      return index;
    },
    changeFscoreFlag(fairitem) {
      if (fairitem.toString().substring(0, 1) === "1") {
        // 室外
        this.dataForm.fscoreFlag = "1"; // 学校
        this.fscoreFlagStatus = true;
      } else {
        this.fscoreFlagStatus = false;
      }
    },
    changeFscoreFlag2(fscoreFlag) {
      if (fscoreFlag === "1") {
        // 学校
        this.dataForm.atsPoints = [];
        //   this.fscoreFlagStatus2 = false
        // } else {
        //   this.fscoreFlagStatus2 = true
      }
    },
  },
};
</script>